package com.shycloud.mido.member.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

import cn.hutool.core.util.StrUtil;
import com.shycloud.mido.member.api.entity.*;
import com.shycloud.mido.member.mapper.*;
import com.shycloud.mido.member.service.OptHardwareSaleService;
import com.shycloud.mido.member.service.ShoppingMallService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import sun.font.FontDesignMetrics;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.member.api.dto.OptHardwareDTO;

import lombok.AllArgsConstructor;

@RestController
@AllArgsConstructor
@RequestMapping("/hardwareSale")
@ApiIgnore
public class HardwareSaleController {

	/** 【硬件销售项目】业务 mapper */
	private final HardwareSaleMapper hardwareSaleMapper;
	/** 运营商权限后台【硬件销售项目】业务 service */
	private final OptHardwareSaleService optHardwareSaleService;
	/** 套餐模块 service */
	private ShoppingMallService shoppingMallService;
	/** 套餐模块 mapper */
	private BasicProductsComboMapper comboMapper;
	/** 套餐商品模块 mapper */
	private BasicComboGoodsMapper comboGoodsMapper;
	/** 硬件模块 mapper */
	private StockDeviceInfoMapper deviceInfoMapper;

	/**
	 * H5 页面获取套餐列表
	 *
	 * @param optId
	 * @return * @author nianhua.jiang
	 * @date 2020/11/17 17:13
	 **/
	@GetMapping("/getH5Comb")
	public R getH5Comb(Integer optId) {

		List result = new ArrayList();
		//用户获取运营商设置的套餐
		List<OptHardwareDTO> list = hardwareSaleMapper.getOptItemList(optId);

		for (OptHardwareDTO item : list) {

			Map<String, Object> map = new HashMap<>();
			//商品明细
			List itemList = new ArrayList();
			map.put("id", item.getId());
			map.put("itemType", item.getItemType());
			map.put("comboName", item.getCustomName());
			map.put("salePrice", item.getSalePrice());
			//处理商品明细字符串
			int index = 0;
			if (item.getItemType().equals("销售")) {
				index += 1;
				itemList.add(index + ". 纠错大师智能硬件 1套");
			}
			if (null != item.getHardwareDuration()) {
				index += 1;
				String endings = item.getHardwareDuration() + "个月";
				if (item.getHardwareDuration() == 0) {
					endings = "永久";
				}
				itemList.add(index + ". 快乐斑马HD App内硬件使用权限 " + endings);
			}
			if (null != item.getVipDuration()) {
				index += 1;
				String endings = item.getVipDuration() + "个月";
				if (item.getVipDuration() == 0) {
					endings = "永久";
				}
				itemList.add(index + ". 快乐斑马HD App内会员资格权限 " + endings);
			}

			if (null != item.getGold()) {
				index += 1;
				String endings = item.getGold() + "个";
				itemList.add(index + ". 快乐斑马HD App内快乐贝数量 " + endings);
			}

			map.put("itemList", itemList);
			result.add(map);
		}
		return new R<>(result);
	}

	@GetMapping("/test")
	public R getH5Comb(String optId) {
		try {
			BufferedImage big = ImageIO.read(new File("D:/back.png"));
			//BufferedImage small = ImageIO.read(new File("D:/code.png"));
			BufferedImage small = createImage("http://192.168.0.127:8080?optId=" + optId);
			Graphics2D g = big.createGraphics();

			//二维码或小图在大图的左上角坐标
			int x = 375;
			int y = 1850;
			Font font = new Font("方正舒体 常规", Font.BOLD, 132);
			g.setFont(font);
			g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
			g.setColor(Color.WHITE);
			g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			String line1 = "佳音教育机构";
			String line2 = "13274341499";
			g.drawString(line1, (big.getWidth() - getWordWidth(font, line1)) / 2, 3900);
			g.drawString(line2, (big.getWidth() - getWordWidth(font, line2)) / 2, 4134);
			g.dispose();
			//为了保证大图背景不变色，formatName必须为"png"
			ImageIO.write(big, "png", new File("C:/Users/ondor/Desktop/combinePic.png"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new R<>();
	}

	//求字符串的宽度(用于居中显示)
	public static int getWordWidth(Font font, String content) {
		FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
		int width = 0;
		for (int i = 0; i < content.length(); i++) {
			width += metrics.charWidth(content.charAt(i));
		}
		return width;
	}

	private static BufferedImage createImage(String content) throws IOException, WriterException {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 1);
		//200是定义的二维码或小图片的大小
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 1500, 1500, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//循环遍历每一个像素点
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
			}
		}

		return image;
	}

	//TODO ====================================== 2020/11/17 nianhua.jiang ADD START==================================//

	/**
	 * 添加套餐
	 *
	 * @param entity
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/17 10:17
	 **/
	@PostMapping("addCombo")
	public R addCombo(@RequestBody HardwareSale entity) {
		return new R(shoppingMallService.addNewComboByH5(entity));
	}

	/**
	 * 小程序添加套餐
	 *
	 * @param basicComboInfo
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/05/26 14:45
	 **/
	@PostMapping("addComboMini")
	public R addCombo(@RequestBody BasicComboInfo basicComboInfo) {

		if (comboMapper.insert(basicComboInfo) == 1) {
			//添加VIP套餐
			BasicComboGoods basicComboGoods = new BasicComboGoods();
			//是赠送商品
			basicComboGoods.setGiftFlag("1");
			//固定VIP商品1天
			basicComboGoods.setGoodsId(21);
			//套餐ID
			basicComboGoods.setComboId(basicComboInfo.getId());
			//商品数量 - VIP时长
			basicComboGoods.setQuantity(basicComboInfo.getVipDuration());
			comboGoodsMapper.insert(basicComboGoods);
		}
		return new R(basicComboInfo.getId());
	}

	/**
	 * 显示套餐列表
	 *
	 * @param page
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/17 15:33
	 **/
	@GetMapping("/getComboList")
	public R getComboList(Page<BasicComboInfo> page, String comboName, String itemType) {
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("is_delete", 0);
		queryWrapper.eq("is_h5", 1);
		if (StrUtil.isNotBlank(comboName)) {
			queryWrapper.eq("combo_name", comboName);
		}
		if (StrUtil.isNotBlank(itemType)) {
			queryWrapper.eq("item_type", itemType);
		}
		return new R<>(comboMapper.selectPage(page, queryWrapper));
	}

	/**
	 * 修改套餐
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/17 15:33
	 **/
	@GetMapping("updCombo")
	public R updCombo(Integer id, String comboName, Boolean isCustomizeVisible, Boolean isCustomizeName, Integer sort) {

		BasicComboInfo basicComboInfo = comboMapper.selectById(id);
		//套餐名称
		basicComboInfo.setComboName(comboName);
		//运营商是否可以自定义可见
		basicComboInfo.setIsCustomizeVisible(isCustomizeVisible);
		//运营商是否可以自定义名字
		basicComboInfo.setIsCustomizeName(isCustomizeName);
		//排序
		basicComboInfo.setSort(sort);
		return new R(comboMapper.updateById(basicComboInfo));

	}

	/**
	 * 启用/禁用
	 *
	 * @param requestMap
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/11/17 16:45
	 **/
	@PostMapping("ableCombo")
	public R ableCombo(@RequestBody Map<String, Object> requestMap) {

		//主键ID
		Integer id = (Integer) requestMap.get("id");
		//状态 0-启用 1-禁用
		String status = (String) requestMap.get("status");
		BasicComboInfo basicComboInfo = comboMapper.selectById(id);
		basicComboInfo.setStatus(status);
		return new R(comboMapper.updateById(basicComboInfo));
	}

	/**
	 * 删除
	 *
	 * @param requestMap
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/11/17 16:45
	 **/
	@PostMapping("delCombo")
	public R delCombo(@RequestBody Map<String, Integer> requestMap) {

		Integer id = requestMap.get("id");

		BasicComboInfo basicComboInfo = comboMapper.selectById(id);
		basicComboInfo.setIsDelete("1");
		return new R(comboMapper.updateById(basicComboInfo));
	}

	/**
	 * 运营商后台获取项目套餐列表 【商品管理】->【硬件销售项目】
	 *
	 * @param page
	 * @param optId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/18 9:31
	 **/
	@GetMapping("/getOptItemList")
	public R getOptItemList(Page<OptHardwareDTO> page, Integer optId) {
		return new R<>(hardwareSaleMapper.getOptItemPage(page, optId));
	}

	/**
	 * 运营商权限修改套餐
	 *
	 * @param entity
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/18 9:34
	 **/
	@PostMapping("/addIgnore")
	public R addIgnore(@RequestBody OptHardwareSale entity) {
		return new R<>(optHardwareSaleService.saveOrUpdate(entity));
	}

	/**
	 * 注册/激活
	 *
	 * @param
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/12/4 10:45
	 **/
	@PostMapping("registerAndActivate")
	public R registerAndActivate(@RequestBody Map<String, String> requestMap) {
		return new R(optHardwareSaleService.registerAndActivate(requestMap));
	}

	//TODO ====================================== 2020/11/17 nianhua.jiang ADD E N D==================================//

	/**
	 * feign 用查询对应商品对应数量的套餐ID，没有返回0
	 *
	 * @param goodsId  商品ID
	 * @param quantity 数量
	 * @return combId 套餐ID
	 * @author nianhua.jiang
	 * @date 2021/5/26 13:48
	 **/
	@GetMapping("checkCombGoods")
	public Integer checkCombGoods(Integer goodsId, Integer quantity) {

		List<BasicComboGoods> basicComboGoods = comboGoodsMapper.selectList(new QueryWrapper<BasicComboGoods>()
				.eq("goods_id", goodsId)
				.eq("quantity", quantity));

		if (basicComboGoods.size() > 0) {
			return basicComboGoods.get(0).getComboId();
		}
		return 0;
	}

	@PostMapping("updStockDeviceInfo")
	public R updStockDeviceInfo(@RequestBody StockDeviceInfo stockDeviceInfo) {
		return new R(deviceInfoMapper
				.update(stockDeviceInfo, new QueryWrapper<StockDeviceInfo>().eq("udid", stockDeviceInfo.getUdid())));
	}

}
